﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows;

namespace DynamicUIFramework
{
    public static class DesignerContext
    {
        static DesignerContext()
        {
            if (File.Exists(UISetting.DataPath))
            {
                try
                {
                    using (Stream stream = new FileStream(UISetting.DataPath, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        IFormatter formatter = new BinaryFormatter();
                        String data = formatter.Deserialize(stream).ToString();
                        isInDesignMode = bool.Parse(data);
                    }
                }
                catch
                {
                    using (Stream stream = new FileStream(UISetting.DataPath, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        IFormatter formatter = new BinaryFormatter();
                        formatter.Serialize(stream, IsInDesignMode);
                    }
                }
            }
        }

        private static bool isChanged = false;
        private static bool isInDesignMode = true;
        public static bool IsInDesignMode
        {
            get { return isInDesignMode; }
            set
            {
                if (isInDesignMode != value)
                {
                    isInDesignMode = value;
                    isChanged = true;

                    using (Stream stream = new FileStream(UISetting.DataPath, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        IFormatter formatter = new BinaryFormatter();
                        formatter.Serialize(stream, IsInDesignMode);
                    }
                }
                if (isChanged)
                {
                    MessageBoxResult result = MessageBox.Show("重启生效，请手动保存修改的东西，是否现在重启动？", "编辑模式", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
                    if (result == MessageBoxResult.Yes)
                    {
                        System.Windows.Application.Current.Shutdown();
                        System.Diagnostics.Process.Start(System.Reflection.Assembly.GetEntryAssembly().Location);
                    }
                }
            }
        }
    }
}
